<template>
  <div class="login-container">
    <div v-if="activeForm === 'login'" class="ms-login">
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on"
        label-position="left">
        <!-- 标题部分 -->
        <div class="title-container">
          <div class="welcome">
            <h1>welcome</h1>
          </div>
          <div class="titlehead" style="padding-right: 100px">
            <h3 class="title" style="color: #4d5067; width: 400px">
              兰州中小企业审核平台
            </h3>
          </div>
          <p style="color: #4d5067; font-weight: 0">
            lanzhouzhongxiaoqiyeshenhepingtai
          </p>
        </div>
        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input autocomplete="off" prefix-icon="el-icon-user-solid" ref="username" v-model="loginForm.username"
            placeholder="用户名" name="username" type="text" tabindex="1" auto-complete="on" />
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input autocomplete="off" prefix-icon="el-icon-lock" :key="passwordType" ref="password"
            v-model="loginForm.password" :type="passwordType" placeholder="密码" name="password" tabindex="2"
            auto-complete="on" @keyup.enter.native="handleLogin" />
          <span class="show-pwd" @click="showPwd"> </span>
        </el-form-item>
        <!-- 图形验证码 -->
        <el-form-item prop="smsCode" class="codeitem">
          <el-input v-model="loginForm.smsCode" placeholder="图形验证码" prefix-icon="el-icon-picture-outline-round"
            style="width: 220px; margin-right: 50px">
          </el-input>
          <div class="codeBtns" @click="refreshCode">
            <IdentifyCode :identify-code="identifyCode"></IdentifyCode>
          </div>
        </el-form-item>
        <!-- 记住密码忘记密码 -->
        <div class="login-check">
          <div class="login-box">
            <el-checkbox v-model="loginForm.remember">记住密码</el-checkbox>
          </div>
        </div>
        <el-form-item >
        <!-- 登录 -->
        <el-button :loading="loading" type="primary" style="
            background-color: #0068ff;
            border-radius: 10px;
            width: 406px;
            margin-left: 0px;
          " @click.native.prevent="handleLogin()">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
//
// import { validUsername } from "@/utils/validate";
// 引入图形验证码组件
import IdentifyCode from "@/components/code/index.vue";
// 引入cookie方法
import { getCookie, setCookie } from "@/utils/cookie";
import { Message } from "element-ui";
import { addadmin, senddx, updatePassword } from "@/api/user";
export default {
  components: {
    IdentifyCode,
  },
  name: "Login",
  data() {
    // 验证码逻辑
    const validateCode = (rule, value, callback) => {
      if (value == "") {
        callback(new Error("请输入验证码"));
      } else if (value.toLowerCase() != this.identifyCode.toLowerCase()) {
        callback(new Error("验证码不正确"));
        this.refreshCode()
        this.loginForm.smsCode = ""
      } else {
        callback();
      }
    };
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error("请输入用户名"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 8) {
        callback(new Error("密码不能少于8位"));
      } else {
        callback();
      }
    };
    return {
      activeForm: "login",
      identifyCode: "", // 验证码
      identifyCodes: "123456789abcdwerwshdjeJKDHRJHKPLMKQ", //验证码随机范围,
      loginForm: {
        username: "",
        password: "",
        remember: false,
      },
      loginRules: {
        // 用户名校验
        username: [
          { required: true, trigger: "blur", message: "请输入您的用户名" },
        ],
        // 密码校验
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
          { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+~`\-={}[\]:;"'<>,.?/\\|])(?=.*[^\s]).{8,}$/, message: '密码必须是8位具有大小写字母、数字和字符', trigger: 'blur' }
        ],
        // 验证码校验
        smsCode: [
          { required: true, trigger: "blur", message: "请输入验证码" },
          { validator: validateCode, trigger: "blur" },
          // { validator: validateCodeWithRefresh, trigger: "blur" },
        ],
      },
      loading: false,
      passwordType: "password",
      redirect: undefined,
      // 注册
      form: {
        phone: "",
        code: "",
        password: "",
        password_confirm: "",
        nickname: "",
      },
      rules: {
        phone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              const reg = /^1[3-9]\d{9}$/;
              if (value === "" || reg.test(value)) {
                callback();
              } else {
                callback(new Error("手机号码格式不正确"));
              }
            },
            trigger: "blur",
          },

        ],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 20, message: "密码长度应为6-20位", trigger: "blur" },

        ],
        password_confirm: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value === this.form.password) {
                callback();
              } else {
                callback(new Error("两次输入的密码不一致"));
              }
            },
            trigger: "blur",
          },
        ],
        nickname: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          { min: 2, max: 20, message: "昵称长度应为2-20位", trigger: "blur" },
        ],
      },
      // 忘记密码表单
      forgetform: {
        forgetphone: "",
        forgetcode: "",
        forgetpassword: "",
        forgetpassword_confirm: "",
      },
      forgetrules: {
        forgetphone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              const reg = /^1[3-9]\d{9}$/;
              if (value === "" || reg.test(value)) {
                callback();
              } else {
                callback(new Error("手机号码格式不正确"));
              }
            },
            trigger: "blur",
          },
        ],
        forgetcode: [
          { required: true, message: "请输入验证码", trigger: "blur" },
        ],
        forgetpassword: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 20, message: "密码长度应为6-20位", trigger: "blur" },
        ],
        forgetpassword_confirm: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value === this.forgetform.forgetpassword) {
                callback();
              } else {
                callback(new Error("两次输入的密码不一致"));
              }
            },
            trigger: "blur",
          },
        ],
      },
      sendingCode: false,
      buttonText: "发送验证码",
      countdown: 0,
    };
  },
  mounted() {
    this.refreshCode();
    this.loadFromLocalStorage()
    // 绑定监听事件
    window.addEventListener("keydown", this.keyDown);
  },
  destroyed() {
    // 销毁事件
    window.removeEventListener("keydown", this.keyDown, false);
  },
  methods: {
    // 去登录
    gologin() {
      this.activeForm = "login";
    },
    // 记住密码,需要在登录的时候调用此方法
    loadFromLocalStorage() {
      // 从本地存储中读取用户名和密码
      const Base64 = require("js-base64").Base64
      this.loginForm.username = localStorage.getItem('username') || ''
      this.loginForm.password = Base64.decode(localStorage.getItem('password') || '')
      //this.loginForm.password = localStorage.getItem('password')
      if (this.loginForm.username && this.loginForm.password) {
        this.loginForm.remember = true
      }
    },
    // 验证码点击刷新方法
    refreshCode() {
      this.identifyCode = ""; // 4位验证码可以根据自己需要来定义验证码位数
      this.makeCode(this.identifyCodes, 4);
    }, // 随机数
    randomNum(min, max) {
      max = max + 1;
      return Math.floor(Math.random() * (max - min) + min);
    }, // 随机生成验证码字符串
    makeCode(data, len) {
      for (let i = 0; i < len; i++) {
        this.identifyCode += data[this.randomNum(0, data.length - 1)];
      }
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          console.log(1);
          const Base64 = require("js-base64").Base64
          let password = Base64.encode(this.loginForm.password) // base64加密
          this.loginForm.password = password
          this.loading = true;
          this.$store
            .dispatch("user/login", this.loginForm)
            .then(() => {
              if (this.loginForm.remember) {
                localStorage.setItem("username", this.loginForm.username);
                localStorage.setItem("password",password);
              } else {
                localStorage.removeItem("username");
                localStorage.removeItem("password");
              }
              this.$router.push("/");
              this.loading = false;
            }).catch(() => {
              this.loading = false
              this.loginForm = {
                username: "",
                password: "",
              }
              this.refreshCode()
            })
        }
      });
    },
    // 点击回车键登录
    keyDown(e) {
      // 回车则执行登录方法 enter键的ASCII是13
      if (e.keyCode == 13) {
        this.handleLogin(); // 定义的登录方法
      }
    },
    // 改变验证码方法
    changecode() {
      this.identifyCode = ""; // 4位验证码可以根据自己需要来定义验证码位数
      this.makeCode(this.identifyCodes, 4);
    }, // 随机数
    randomNum(min, max) {
      max = max + 1;
      return Math.floor(Math.random() * (max - min) + min);
    }, // 随机生成验证码字符串
    makeCode(data, len) {
      for (let i = 0; i < len; i++) {
        this.identifyCode += data[this.randomNum(0, data.length - 1)];
      }
    },
    // 注册提交表单
    submitForm() {
      this.$refs.submitValidation.validate((valid) => {
        if (valid) {
          this.loading = true;
          // 验证通过，提交表单
          console.log(this.form);
          addadmin({
            phone: this.form.phone,
            password: this.form.password,
            username: this.form.nickname,
            yzm: this.form.code,
          })
            .then((res) => {
              if (res.state === 40900) {
                this.$message.error("注册失败此号码已被占用");
                this.form = "";
              } else {
                this.$message.success("注册成功");
                this.form = "";
              }
            })
            .catch((error) => {
              console.log(error);
              this.$message.error("注册失败，请检查输入信息并稍后重试");
            });
        } else {
          console.log("验证失败");
          return false;
        }
      });
    },
    // 找回密码
    submitforgetForm() {
      this.$refs.forgetform.validate((valid) => {
        if (valid) {
          updatePassword({
            password: this.forgetform.forgetpassword,
            phone: this.forgetform.forgetphone,
            yzm: this.forgetform.forgetcode,
          })
            .then((res) => {
              this.$message.success("修改密码成功");
              this.forgetform = "";
            })
            .catch((error) => { });
        }
      });
    },
    sendforgetCode() {
      this.$message.success("发送验证码成功");
      senddx({ phone: this.forgetform.forgetphone }).then((res) => {
      });
    },
    sendCode() {
      if (!this.checkformphone()) {
        return;
      }
      senddx({ phone: this.form.phone }).then((res) => {
      });
      // TODO: 发送验证码的逻辑
      this.countdown = 60;
      this.sendingCode = true;
      const timer = setInterval(() => {
        if (this.countdown === 0) {
          clearInterval(timer);
          this.sendingCode = false;
          this.buttonText = "重新发送";
        } else {
          this.countdown--;
          this.buttonText = `${this.countdown}s后重新发送`;
        }
      }, 1000);
    },
    // 请输入验证码之前填写手机号码
    checkformphone() {
      if (this.form.phone === "") {
        return false;
      }
      return true;
    },
    checkforgetphone() {
      if (this.forgetform.forgetphone === "") {
        return false;
      }
      return true;
    },
    //////////////////////////////
  },
};
</script>

<style lang="scss">
$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
    width: 100%;
  }
}

/* reset element-ui css */
.login-container {
  background: url("~@/images/loginbg.jpg");
  background-size: 100%;
  position: relative;
  width: 100%;
  height: 100%;

  .el-input {
    display: inline-block;
    height: 100%;
    width: 78%;

    input {
      color: black;
    }
  }
}
</style>
<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  // position:absolute;
  // top: 0;
  min-height: 100%;
  width: 100%;
  // background-color: $bg;
  overflow: hidden;

  .ms-login {
    // background-color: red;
    position: absolute;
    left: 50%;
    top: 50%;
    width: 406px;
    margin: -268px 40px 0 135px;
    border-radius: 5px;
    // background: rgba(255, 255, 255, 0.8);
    overflow: hidden;
  }

  .login-form {
    // background-color:green;
    // margin-top: 90px;
    // transform: translate(50%, 50%);
    width: 520px;
    height: 100%;
    // max-width: 100%;
    // // position: absolute;
    // // padding: 0px 0px 0 58px;
    // overflow: hidden;
  }

  .tips {
    text-align: center;
    margin-right: 65px;
  }

  // 随机验证码
  .codeBtns {
    width: 130px;
    display: inline-block;
    background-color: #e9eff9;
    height: 40px !important;
    margin-left: 5px;
    vertical-align: -14px;
    color: #0068ff;
    cursor: pointer;
  }

  // 记住密码
  .login-check {
    display: flex;
    justify-content: space-between;
    margin-bottom: 30px;
  }

  .login-check .login-box {
    font-size: 12px !important;
  }

  .login-span {
    color: #0068ff;
    font-size: 12px;
    cursor: pointer;
  }

  .login-span:hover {
    color: #2440b3;
  }

  // 输入框图标背景色
  .svg-container {
    padding: 6px 15px 6px 15px;
    color: #dee0e7;
    vertical-align: middle;
    width: 45px;
    border-radius: 5px;
    border-top: transparent;
    background-color: #fff;
    display: inline-block;
  }

  .title-container {

    // 标题内容
    .welcome {
      width: 100%;
      height: 60px;
      font-size: 40px;
      font-family: Arial;
      font-weight: 400;
      color: #f1f1f1;
      line-height: 20px;
      opacity: 0.7;
      margin-bottom: -20px;
      padding-left: 30px;
    }

    .title {
      padding-right: 18px;
      width: 400px;
      height: 38px;
      font-size: 40px;
      font-family: Microsoft YaHei;
      font-weight: bold;
      color: red;
      line-height: 69px;
    }

    p {
      width: 400px;
      margin-left: 70px;
      color: #4d5067;
      margin-top: -20px;
    }

    position: relative;

    .title {
      display: block;
      width: 500px;
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
<style lang="scss">
.login-container {

  // position: relative;
  .outsideregister {
    margin-right: 200px;
    margin-top: 10px;
    // background-color: red;
    margin-left: 940px;

    .register-form {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 400px;

      .el-form-item {
        width: 100%;

        .el-input {
          width: 100%;
        }

        .el-button {
          margin-left: 10px;
        }
      }

      .registertitle {
        h3 {
          margin-top: -20px;
        }

        .titlepbox {
          margin-top: -36px;
        }

        .titlebox {
          display: flex;
          justify-content: center;

          h1 {
            height: 60px;
            font-size: 77px;
            font-family: Arial;
            font-weight: 700;
            color: #f1f1f1;
            // line-height: 20px;
            opacity: 0.7;
          }
        }
      }

      .primary {
        width: 398px;
        margin-right: 6px;
        background: #0068ff;
        border-radius: 10px;
      }

      .registertips {
        span {
          cursor: pointer;
          color: #0068ff;
          font-size: 12px;
        }
      }
    }
  }
}
</style>
<style lang="scss">
.login-container {
  .forgetformbox {
    margin-left: 934px;
    margin-top: 44px;

    .forget-form {
      // background-color: red;
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 400px;

      .el-form-item {
        width: 100%;

        .el-input {
          width: 100%;
        }

        .el-button {
          margin-left: 10px;
        }
      }

      .forgettitle {
        h3 {
          margin-top: -20px;
        }

        .forgettitlepbox {
          margin-top: -36px;
        }

        .forgettitlebox {
          display: flex;
          justify-content: center;

          h1 {
            height: 60px;
            font-size: 77px;
            font-family: Arial;
            font-weight: 700;
            color: #f1f1f1;
            // line-height: 20px;
            opacity: 0.7;
          }
        }
      }
    }

    .forgetprimary {
      width: 398px;
      margin-right: 6px;
      background: #0068ff;
      border-radius: 10px;
    }

    .forgettips {
      span {
        cursor: pointer;
        color: #0068ff;
        font-size: 12px;
      }
    }
  }
}
</style>